#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
FlaSam Code

2007 2007-6-23 下午03:28:39
'''

from django.contrib.auth.models import User, Group
from django.core import validators
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from middleware import threadlocals_middleware
from utils import ad_utils
import datetime


class UpdateException(Exception):
    pass

class AdPlace(models.Model):
    
    place_name = models.CharField(verbose_name='地区名称', max_length=1024, unique=True)
    place_parent = models.ForeignKey('self', verbose_name='上级地区', null=True, related_name='child_set', blank=True)
    
    #history = audit.AuditTrail()

    def __unicode__(self):
        p_list = self._recurse_for_parents(self)
        p_list.append(self.place_name)
        return self.get_separator().join(p_list)
    
    def _recurse_for_parents(self, cat_obj):
        p_list = []
        if cat_obj.place_parent_id:
            p = cat_obj.place_parent
            p_list.append(p.place_name)
            more = self._recurse_for_parents(p)
            p_list.extend(more)
        if cat_obj == self and p_list:
            p_list.reverse()
        return p_list
    
    def _parents_repr(self):
        p_list = self._recurse_for_parents(self)
        return self.get_separator().join(p_list)
    _parents_repr.short_description = "Tag parents"
    
    def get_separator(self):
        return '-'


    def save(self):
        p_list = self._recurse_for_parents(self)
        if self.place_name in p_list:
            raise validators.ValidationError(u"不能将自身作为地区父类")
        super(AdPlace, self).save()
    
    class Admin:
        list_display = ('place_name', 'place_parent')
        ordering = ['place_parent_id', 'plcae_name']
        #pass
        
    class Meta:
        permissions = (
                       ('can_add_place', u'允许 添加 地点区域'), \
                       ('can_del_place', u'允许 删除 地点区域'), \
                       ('can_edit_place', u'允许 编辑 地点区域'), \
                       )
        
#===============================================================================
#    class History:
#        pass
#===============================================================================

class AdUserProfileManager(models.Manager):
    
    def is_expire(self):
        '''
        check user is expire ?
        '''
        pass
    
    def has_profile(self, u_name):
        '''
        check user has profile info
        @param u_name: username
        '''
        pass
    
    def is_valid(self):
        '''
        check user is baned ?
        just check user_state col
        '''
        pass
    
    def is_group_member(self, u, g):
        group_list = []
        for x in User.objects.get(username=u).groups.all():
            group_list.append(x)
        
        if g in group_list:
            return True
        else:
            return False
        
    def has_vaild_perm(self, u, p):
        '''
        
        @param p: permissions code name
        '''
        try:
            user_obj = User.objects.get(username=str(u))
        except ObjectDoesNotExist:
            return False
        
        if user_obj.has_perm(p):
            return True
        else:
            return False
    
    def get_user_uuid(self):
        '''
        return user uuid
        '''
        pass
    
    def get_user_place(self):
        pass
    
    def get_user_groups(self):
        pass
    
    #FIXME: something wrong
#===============================================================================
#    def get_user_ext_info(self):
#        
#        if self.user_type == 'manager':
#            try:
#                return AdManagerInfo.objects.get(username__exact=self.user)
#            except AdManagerInfo.DoesNotExit:
#                return None
#        elif self.user_type == 'agent':
#            try:
#                return AdAgentInfo.objects.get(username__exact=self.user)
#            except AdAgentInfo.DoesNotExit:
#                return None
#        elif self.user_type == 'player':
#            try:
#                return AdPlayerInfo.objects.get(username__exact=self.user)
#            except AdPlayerInfo.DoesNotExit:
#                return None
#        else:
#            return False
#===============================================================================

USER_TYPE_CHOICES = (
             ('manager', '管理员'), \
             ('agent', '广告代理商'), \
             ('client', '广告客户'), \
             ('player', '广告播放者')
             )

class AdUserProfile(models.Model):
    
    user = models.ForeignKey(User, unique=True, related_name='user')
    
    creator = models.ForeignKey(User, \
                                null=True, \
                                blank=False, \
                                related_name='creator', \
                                verbose_name='创建者', \
                                help_text='该用户的创建者,其他的管理员将不能够删除或编辑该用户')
    
    last_modify_by = models.ForeignKey(User,
                                       null=True, \
                                       blank=False,\
                                       related_name='last_midify_by', \
                                       verbose_name='最后的编辑者', \
                                       help_text='该条目的最后编辑者') 
    
    last_modify_datetime = models.DateTimeField(auto_now=True, \
                                                verbose_name='最后一次被修改的时间', \
                                                help_text='该用户最后的信息一次被修改的时间')

    user_start_date = models.DateField(auto_now_add=True, \
                                       verbose_name='创建时间', \
                                       help_text='用户创建时间')
    user_expire_date = models.DateField(blank=True, \
                                        verbose_name='过期时间', \
                                        default=datetime.date(2012, 12, 12), \
                                        help_text='过期后用户将不再被处理, 日期格式:年-月-日, 例如2007-4-30 或者 2007-04-30')

    user_place = models.ForeignKey(AdPlace, \
                                   verbose_name='用户所在地', \
                                   help_text='如果用户所在城市不在本列表内,请选择用户所在省,然后通知管理员添加您所在市', \
                                   null=True
                                   )
    user_desc = models.TextField(blank=True, \
                                 verbose_name='用户注释及说明', \
                                 help_text='用户说明')
    user_uuid = models.CharField(max_length=38, \
                                 default=ad_utils.mk_uuid, \
                                 editable=False, \
                                 blank=True, \
                                 unique=True)
    user_type = models.CharField(blank=False, \
                                 max_length=10, \
                                 verbose_name='用户类型', \
                                 help_text='用户的类型确定了用户详细记录表,请谨慎选择该选项', 
                                 choices=USER_TYPE_CHOICES)
    
    objects = AdUserProfileManager()
    
    #history = audit.AuditTrail()
    
    def save(self):
        if self.id:
            self.last_modify_by = threadlocals_middleware.get_current_user()
        else:
            self.creator = threadlocals_middleware.get_current_user()
        super(AdUserProfile, self).save()
    
        
    class History:
        pass
    
    class Meta:
        permissions = (
                       ('can_add_userprofile', u'允许 添加 用户属性'), \
                       ('can_edit_userprofile', u'允许 编辑 用户属性'), \
                       ('can_del_userprofile', u'允许 删除 用户属性'), \
                       ('can_change_user_state', u'允许 改变 用户状态'), \
                       ('can_change_user_expire', u'允许 修改 用户过期时间'), \
                       ('can_change_user_permssions', u'允许 修改 用户权限')
                       )
    class Admin:
        list_display = ('user', 'creator','user_start_date', 'user_expire_date', 'user_place', 'user_uuid')
    
    def __str__(self):
        return str(self.user)
    
#===============================================================================
#    def __unicode__(self):
#        return self.user
#===============================================================================
    
USER_POSITION_CHOICES= (
                       (u'manager', u'总经理'), \
                       (u'officer', u'部门经理'), \
                       (u'employee', u'普通职员'), \
                       (u'unknow', u'未知')
                       )

class AdManagerInfo(models.Model):
    
    username = models.OneToOneField(User)

    user_dept = models.CharField(verbose_name='部门', \
                                 max_length=30, \
                                 blank=False, \
                                 help_text='职员在公司所属部门')
    user_position = models.CharField(verbose_name='职位', \
                                     choices=USER_POSITION_CHOICES, \
                                     max_length=30, \
                                     blank=False, \
                                     help_text='职员在公司的职位', \
                                     default='unknow')
    user_cname = models.CharField(verbose_name='中文名', \
                                  max_length=10, \
                                  blank=False, \
                                  help_text='职员的中文名')
    user_phone = models.CharField(max_length=256, \
                                  verbose_name='固定电话', \
                                  blank=False, \
                                  help_text='职员固定联系电话')    
    user_mophone = models.CharField(max_length=256, \
                                    verbose_name='移动电话', \
                                    blank=False, \
                                    help_text='职员移动联系电话')

        
#    def __str__(self):
#        return self.username

    def __unicode__(self):
        return str(self.username)
    
    class Admin:
        list_display = ('username', 'user_cname', 'user_dept', 'user_position')


class AdAgentInfo(models.Model):
    
    username = models.OneToOneField(User)
    
    #manager  = models.ForeignKey(User, related_name='agent_manager', blank=True, null=True)
    
    user_corp_name = models.CharField(verbose_name='公司名称', \
                                      max_length=256, \
                                      blank=False, \
                                      help_text='代理公司名称')
    
    user_corp_place = models.ForeignKey(AdPlace, \
                                        verbose_name='公司所在地', \
                                        help_text='代理公司所在地', \
                                        blank=False, \
                                        null=True)
    
    user_corp_address = models.TextField(verbose_name='地址', help_text='代理公司详细地址', blank=True)
        
    user_position = models.CharField(verbose_name='职位', \
                                     choices=USER_POSITION_CHOICES, \
                                     max_length=30, \
                                     blank=False, \
                                     help_text='代理公司联系人所在职位', \
                                     default='unknow')
    user_cname = models.CharField(verbose_name='中文名', \
                                  max_length=10, \
                                  blank=False, \
                                  help_text='代理公司联系人中文名')
    user_phone = models.CharField(max_length=256, \
                                  verbose_name='固定电话', \
                                  blank=False, \
                                  help_text='代理公司固定联系电话')    
    user_mophone = models.CharField(max_length=256, \
                                    verbose_name='移动电话', \
                                    blank=False, \
                                    help_text='代理公司联系人移动电话')
    
#    def save(self):
#        
#        if self.id:
#            pass
#        else:
#            self.manager = get_current_user()
#            
#        super(AdAgentInfo, self).save()
 
    def __unicode__(self):
        return str(self.username)
    
    class Admin:
        list_display= ('username', 'user_corp_name', 'user_cname')

USER_CORP_LEVEL_CHOICES = (
                           (0, '未知'), \
                           (1, '差'), \
                           (2, '较差'), \
                           (3, '一般'), \
                           (4, '较好'), \
                           (5, '好')
                           )

class AdPlayerInfo(models.Model):
    
    username = models.OneToOneField(User)
    
    #manager = models.ForeignKey(User, related_name='player_manager', blank=False, null=True)
    
    user_position = models.CharField(verbose_name='职位', \
                                     choices=USER_POSITION_CHOICES, \
                                     max_length=30, \
                                     blank=False, \
                                     help_text='广告播放者联系人职位', \
                                     default='unknow')
    user_cname = models.CharField(verbose_name='中文名', \
                                  max_length=10, \
                                  blank=False, \
                                  help_text='广告播放者联系人中文名')
    user_phone = models.CharField(max_length=256, \
                                  verbose_name='固定电话', \
                                  blank=False, \
                                  help_text='广告播放者固定联系电话')    
    user_mophone = models.CharField(max_length=256, \
                                    verbose_name='移动电话', \
                                    blank=False, \
                                    help_text='广告播放者联系人移动电话')
    
    user_corp_name = models.CharField(verbose_name='公司名称', \
                                      max_length=256, \
                                      blank=False, \
                                      help_text='广告播放者名称, 公司名称或者是网吧名称')
    user_corp_place = models.ForeignKey(AdPlace, \
                                        verbose_name='公司所在地', \
                                        help_text='广告播放者所在地', \
                                        blank=False, \
                                        null=True)
    
    user_corp_level = models.SmallIntegerField(verbose_name='级别', \
                                               choices=USER_CORP_LEVEL_CHOICES, \
                                       help_text='公司或网吧的级别(按照客流量,或者所在地繁华程度评价)', blank=False)
    
    user_corp_terminal_amount = models.IntegerField(verbose_name='终端数量', \
                                                    help_text='公司或网吧可供播放广告的终端数量', \
                                                    blank=False)
    
    user_corp_address = models.TextField(verbose_name='地址', help_text='公司或者网吧的详细地址', blank=False)
    
    
    def __unicode__(self):
        return str(self.username)
    
    class Admin:
        list_display = ('username', 'user_corp_name', 'user_cname')


class AdClientInfo(models.Model):
    
    
    username = models.OneToOneField(User)
    
    #manager = models.ForeignKey(User, related_name='client_manager', blank=False, null=True)
    
    user_position = models.CharField(verbose_name='职位', \
                                     choices=USER_POSITION_CHOICES, \
                                     max_length=30, \
                                     blank=False, \
                                     help_text='广告客户联系人职位', \
                                     default='unknow')
    user_cname = models.CharField(verbose_name='中文名', \
                                  max_length=10, \
                                  blank=False, \
                                  help_text='广告客户联系人中文名')
    user_phone = models.CharField(max_length=256, \
                                  verbose_name='固定电话', \
                                  blank=False, \
                                  help_text='广告客户固定联系电话')    
    user_mophone = models.CharField(max_length=256, \
                                    verbose_name='移动电话', \
                                    blank=False, \
                                    help_text='广告客户联系人移动电话')
    
    user_corp_name = models.CharField(verbose_name='公司名称', \
                                      max_length=256, \
                                      blank=False, \
                                      help_text='广告客户公司名称')
    user_corp_place = models.ForeignKey(AdPlace, \
                                        verbose_name='公司所在地', \
                                        help_text='公告公司所在地', \
                                        blank=False, \
                                        null=True)
    
    user_corp_address = models.TextField(verbose_name='地址', help_text='公司详细地址', blank=True)
    
    def __unicode__(self):
        return str(self.username)
    
    class Admin:
        list_display = ('username', 'user_corp_name', 'user_cname')
        
def get_group_members(i):
    group_obj = Group.objects.get(id=i) #@UndefinedVariable
    return User.objects.filter(groups=group_obj)
    

